//
//  WJTutorialViewController.swift
//  PDFSign
//
//  Created by 李永彬 on 2025/10/21.
//

import UIKit
import SnapKit

class WJTutorialViewController: UIViewController {
    
    // MARK: - Lazy UI Components
    private lazy var scrollView: UIScrollView = {
        let scrollView = UIScrollView()
        scrollView.delegate = self
        scrollView.isPagingEnabled = true
        scrollView.showsHorizontalScrollIndicator = false
        scrollView.bounces = false
        return scrollView
    }()
    
    // 自定义长方形 pageControl
    private lazy var pageControl: UIView = {
        let view = UIView()
        return view
    }()
    
    private lazy var pageIndicators: [UIView] = []
    
    private lazy var continueButton: UIButton = {
        let button = UIButton(type: .system)
        button.setTitle("continue", for: .normal)
        button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 18)
        button.backgroundColor = UIColor(hex: "#1F87F6")
        button.setTitleColor(.white, for: .normal)
        button.layer.cornerRadius = 25
        button.layer.masksToBounds = true
        button.addTarget(self, action: #selector(continueButtonTapped), for: .touchUpInside)
//        button.alpha = 0
        return button
    }()
    
    // MARK: - 子控制器数组
    private var childPageViewControllers: [WJTutorialPageViewController] = []
    
    // MARK: - 当前页面索引
    private var currentPageIndex: Int = 0
    
    // MARK: - Lifecycle
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        setupChildViewControllers()
        setupCustomPageControl()
    }
    
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        
        // 更新子控制器的frame
        let pageWidth = view.frame.width
        let scrollViewHeight = scrollView.frame.height
        
        for (index, pageVC) in childPageViewControllers.enumerated() {
            pageVC.view.frame = CGRect(
                x: pageWidth * CGFloat(index),
                y: 0,
                width: pageWidth,
                height: scrollViewHeight
            )
        }
        
        // 更新scrollView内容大小
        scrollView.contentSize = CGSize(
            width: pageWidth * CGFloat(childPageViewControllers.count),
            height: scrollViewHeight
        )
    }
    
    // MARK: - Setup Methods
    private func setupUI() {
        view.backgroundColor = UIColor(hex: "#E7F2FE")
        
        view.addSubview(scrollView)
        view.addSubview(pageControl)
        view.addSubview(continueButton)

        pageControl.snp.makeConstraints { make in
            make.top.equalTo(view.safeAreaLayoutGuide.snp.top).offset(30)
            make.centerX.equalToSuperview()
            make.height.equalTo(6) // 长方形高度
            make.width.equalTo(200)
        }
        
        scrollView.snp.makeConstraints { make in
            make.top.equalTo(pageControl.snp.bottom).offset(10)
            make.leading.trailing.equalToSuperview()
            make.bottom.equalTo(continueButton.snp.top).offset(-20)
        }
        
        continueButton.snp.makeConstraints { make in
            make.bottom.equalTo(view.safeAreaLayoutGuide.snp.bottom).offset(-30)
            make.centerX.equalToSuperview()
            make.width.equalTo(200)
            make.height.equalTo(50)
        }
    }
    
    // 设置自定义长方形 pageControl
    private func setupCustomPageControl() {
        // 清除之前的指示器
        pageIndicators.forEach { $0.removeFromSuperview() }
        pageIndicators.removeAll()
        
        let pageCount = childPageViewControllers.count
        let indicatorWidth: CGFloat = 75
        let indicatorHeight: CGFloat = 4
        let spacing: CGFloat = 8
        
        // 计算总宽度用于居中
        let totalWidth = CGFloat(pageCount) * indicatorWidth + CGFloat(pageCount - 1) * spacing
        
        pageControl.snp.updateConstraints { make in
            make.height.equalTo(indicatorHeight)
            make.width.equalTo(totalWidth)
        }
        
        // 创建指示器
        for i in 0..<pageCount {
            let indicator = UIView()
            indicator.backgroundColor = i == 0 ? UIColor(hex: "#1F87F6") : UIColor(hex: "#121212", alpha: 0.3)
            indicator.layer.cornerRadius = 3
            indicator.layer.masksToBounds = true
            
            pageControl.addSubview(indicator)
            pageIndicators.append(indicator)
            
            indicator.snp.makeConstraints { make in
                make.width.equalTo(indicatorWidth)
                make.height.equalTo(indicatorHeight)
                make.centerY.equalToSuperview()
                make.leading.equalToSuperview().offset(CGFloat(i) * (indicatorWidth + spacing))
            }
        }
    }
    
    // 更新 pageControl 当前页
    private func updateCustomPageControl(currentPage: Int) {
        for (index, indicator) in pageIndicators.enumerated() {
            UIView.animate(withDuration: 0.3) {
                indicator.backgroundColor = index == currentPage ? .systemBlue : .lightGray
                
                // 可选：添加缩放动画效果
                if index == currentPage {
                    indicator.transform = CGAffineTransform(scaleX: 1.2, y: 1.2)
                } else {
                    indicator.transform = .identity
                }
            }
        }
    }
    
    // 跳转到指定页面
    private func scrollToPage(_ pageIndex: Int, animated: Bool = true) {
        let pageWidth = view.frame.width
        let offset = CGPoint(x: pageWidth * CGFloat(pageIndex), y: 0)
        scrollView.setContentOffset(offset, animated: animated)
    }
    
    private func setupChildViewControllers() {
        // 禁用自动调整内容插入
        scrollView.contentInsetAdjustmentBehavior = .never
        
        // 创建三个引导页子控制器
        let page1 = WJTutorialPageViewController()
        page1.configureWith(description: "Sign in a tap \nYour signature, anytime",
                          imageName: "guide_icon_1")
        
        let page2 = WJTutorialPageViewController()
        page2.configureWith(description: "Documents, simplified \nSign and send in seconds",
                          imageName: "guide_icon_2")
        
        let page3 = WJTutorialPageViewController()
        page3.configureWith(description: "Always secure \nYour signature, your \ncontrol",
                          imageName: "guide_icon_3")
        
        let page4 = WJTutorialSignPageViewController()
        
        let pages = [page1, page2, page3, page4]
        
        // 设置 scrollView 内容大小
        let pageWidth = view.frame.width
        let scrollViewHeight = scrollView.frame.height
        
        scrollView.contentSize = CGSize(
            width: pageWidth * CGFloat(pages.count),
            height: scrollViewHeight
        )
        
        // 添加子控制器
        for (index, pageVC) in pages.enumerated() {
            addChild(pageVC)
            scrollView.addSubview(pageVC.view)
            pageVC.didMove(toParent: self)
            
            // 设置子控制器视图的frame，考虑安全区域
            pageVC.view.frame = CGRect(
                x: pageWidth * CGFloat(index),
                y: 0,
                width: pageWidth,
                height: scrollViewHeight
            )
            
            childPageViewControllers.append(pageVC)
        }
    }
    
    // MARK: - Actions
    @objc private func continueButtonTapped() {
        let isLastPage = currentPageIndex == childPageViewControllers.count - 1
        
        if isLastPage {
            // 最后一页：跳转到主界面
            let vc = WJMainTabViewController()
            if let window = view.window {
                window.rootViewController = vc
                UIView.transition(with: window, duration: 0.3, options: .transitionCrossDissolve, animations: nil)
            }
            
            UserDefaults.standard.set(true, forKey: guideKey)
            UserDefaults.standard.synchronize()
            if !WJUserManager.shared.isVIP {
                DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
                    var vc = RemoteConfigValues.getCurrentPurchaseVC()
                    let nav = WJNavigationController(rootViewController: vc)
                    nav.modalPresentationStyle = .fullScreen
                    vc.dimissAction = {
                        let vc = WJPurchaseDiscountViewController()
                        let nav = WJNavigationController(rootViewController: vc)
                        nav.modalPresentationStyle = .fullScreen
                        UIApplication.topViewController()?.present(nav, animated: true)
                        WJUserManager.shared.showedDiscountPlan = true
                    }
                    UIApplication.topViewController()?.present(nav, animated: true)
                }
            }
        } else {
            // 不是最后一页：跳转到下一页
            let nextPageIndex = currentPageIndex + 1
            scrollToPage(nextPageIndex)
        }
    }
}

// MARK: - UIScrollViewDelegate
extension WJTutorialViewController: UIScrollViewDelegate {
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        let pageIndex = round(scrollView.contentOffset.x / view.frame.width)
        let currentPage = Int(pageIndex)
        
        // 更新当前页面索引
        currentPageIndex = currentPage
        
        // 更新自定义 pageControl
        updateCustomPageControl(currentPage: currentPage)
        
        // 在最后一页显示开始按钮
//        if pageIndex == CGFloat(childPageViewControllers.count - 1) {
//            UIView.animate(withDuration: 0.3) {
//                self.continueButton.alpha = 1.0
//            }
//        } else {
//            UIView.animate(withDuration: 0.3) {
//                self.continueButton.alpha = 1.0 // 改为一直显示，但功能不同
//            }
//        }
    }
    
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        let pageIndex = round(scrollView.contentOffset.x / view.frame.width)
        currentPageIndex = Int(pageIndex)
    }
    
    func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) {
        let pageIndex = round(scrollView.contentOffset.x / view.frame.width)
        currentPageIndex = Int(pageIndex)
    }
}
